<?php

class UniqueIDGenerator
{
    /**
     * 基于时间戳、随机数和服务器信息生成不重复的唯一ID
     * @return string
     */
    public static function generateUniqueID(): string
    {
        $time = microtime(true); // 获取当前时间（秒 + 微秒）
        $random = mt_rand(100000, 999999); // 随机数
        $serverInfo = substr(md5(php_uname() . uniqid('', true)), 0, 8); // 服务器信息哈希
        return sprintf('%s-%s-%s', $time, $random, $serverInfo);
    }

    /**
     * 生成短唯一ID，适合高效存储需求
     * @return string
     */
    public static function generateShortUniqueID(): string
    {
        return uniqid(); // 基于微秒时间生成唯一ID
    }

    /**
     * 基于UUID生成全局唯一ID（UUIDv4）
     * @return string
     */
    public static function generateUUID(): string
    {
        $data = random_bytes(16);
        $data[6] = chr((ord($data[6]) & 0x0f) | 0x40); // 设置UUID版本号为4
        $data[8] = chr((ord($data[8]) & 0x3f) | 0x80); // 设置变体
        return sprintf(
            '%08x-%04x-%04x-%04x-%12s',
            unpack('N1', substr($data, 0, 4))[1],
            unpack('n1', substr($data, 4, 2))[1],
            unpack('n1', substr($data, 6, 2))[1],
            unpack('n1', substr($data, 8, 2))[1],
            bin2hex(substr($data, 10, 6))
        );
    }

    /**
     * 基于分布式环境生成唯一ID（雪花算法简化版）
     * @param int $datacenterId 数据中心ID (0-31)
     * @param int $workerId 工作节点ID (0-31)
     * @return string
     */
    public static function generateSnowflakeID(int $datacenterId = 0, int $workerId = 0): string
    {
        if ($datacenterId > 31 || $datacenterId < 0 || $workerId > 31 || $workerId < 0) {
            throw new InvalidArgumentException('Datacenter ID and Worker ID must be between 0 and 31.');
        }

        $timestamp = (int)(microtime(true) * 1000); // 当前毫秒时间戳
        $datacenterShift = 5; // 数据中心位移
        $workerShift = 10;    // 工作节点位移
        $sequence = mt_rand(0, 4095); // 序列号 (12位)

        return (string)(
            ($timestamp << 22) |
            ($datacenterId << $datacenterShift) |
            ($workerId << $workerShift) |
            $sequence
        );
    }
}

// 测试用例
/*echo "Unique ID: " . UniqueIDGenerator::generateUniqueID() . PHP_EOL;
echo "Short Unique ID: " . UniqueIDGenerator::generateShortUniqueID() . PHP_EOL;
echo "UUID: " . UniqueIDGenerator::generateUUID() . PHP_EOL;
echo "Snowflake ID: " . UniqueIDGenerator::generateSnowflakeID(1, 1) . PHP_EOL;*/
